package account

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/spf13/cast"
	"gorm.io/gorm"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type CreateAccountApiLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateAccountApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateAccountApiLogic {
	hostname, _ := os.Hostname()
	return &CreateAccountApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateAccountApiLogic) CreateAccountApi(req *types.CreateAccountReq) (resp string, err error) {
	_, err = dao.AccountEntity.WithContext(l.ctx).Where(dao.AccountEntity.Username.Eq(req.Username)).First()
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		l.Logger.Error(req.Username + "存在,不能重复")
		return "", errors.New("账号存在,不能重复")
	}
	if req.Password != req.ConfirmPassword {
		return "", errors.New("两次密码不一致")
	}
	// 密码加密处理
	salt := utils.GeneratorString(utils.GeneratorRandom(5, 10))
	newPassword := utils.Md5(req.Password, salt)
	if err = dao.AccountEntity.WithContext(l.ctx).
		Omit(dao.AccountEntity.LastLoginIP, dao.AccountEntity.LastLoginDate).
		Create(&model.AccountEntity{
			Username:    req.Username,
			Password:    newPassword,
			Salt:        salt,
			AccountType: req.AccountType,
		}); err != nil {
		l.Logger.Error("创建账号失败" + err.Error())
		return "", errors.New("创建失败")
	}
	return "操作成功", nil
}

func (l *CreateAccountApiLogic) CreateAccount(tx *dao.QueryTx, username, password, avatar string, accountType, enterpriseId, customerId int64) error {
	// 密码加密处理
	_, err := tx.AccountEntity.WithContext(l.ctx).Where(dao.AccountEntity.Username.Eq(username)).First()
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("用户名已经存在")
	}
	accountId := cast.ToInt64(l.ctx.Value("accountId")) // 当前登录用户id
	salt := utils.GeneratorString(utils.GeneratorRandom(5, 10))
	newPassword := utils.Md5(password, salt)
	if err = tx.AccountEntity.WithContext(l.ctx).
		Omit(dao.AccountEntity.LastLoginIP, dao.AccountEntity.LastLoginDate).
		Create(&model.AccountEntity{
			Username:     username,
			Password:     newPassword,
			ParentID:     accountId,
			Salt:         salt,
			Avatar:       avatar,
			AccountType:  accountType,
			EnterpriseID: enterpriseId, // 企业id,enterprise表主键id
			CustomerID:   customerId,   // 客户id,关联到enterprise_customer表主键id
		}); err != nil {
		return err
	}
	return nil
}
